<script setup>
import { ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import logger from '@/utils/logger'
import { saveDealerGoodsStore } from '@/api/goods'
import { fetchGoodsList } from '@/api/goods'

const props = defineProps({
  initialData: {
    type: Object,
    default: null,
  },
})

const emit = defineEmits(['success', 'close'])

// 表单数据
const formData = ref({
  dealerGoodsStoreId: '', // 库存ID，编辑时使用
  dealerGoodsId: '', // 商品ID
  dealerGoodsName: '', // 商品名称，用于显示
  periodStartingDate: '', // 起始有效期
  periodEndDate: '', // 结束有效期
  points: 0, // 积分
  quantity: 1, // 数量
  isSale: true, // 是否可售
})

// 商品列表，用于选择商品
const goodsList = ref([])
const goodsLoading = ref(false)
const selectedGoods = ref(null)

// 表单验证规则
const rules = {
  dealerGoodsId: [{ required: true, message: '请选择商品', trigger: 'change' }],
  periodStartingDate: [{ required: true, message: '请选择起始有效期', trigger: 'change' }],
  periodEndDate: [{ required: true, message: '请选择结束有效期', trigger: 'change' }],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' },
  ],
  points: [
    { required: true, message: '请输入积分', trigger: 'blur' },
    { type: 'number', min: 0, message: '积分不能为负数', trigger: 'blur' },
  ],
}

const formRef = ref(null)

// 初始化数据，用于编辑模式
const initFormData = () => {
  if (props.initialData) {
    // 深拷贝初始数据
    const initialData = JSON.parse(JSON.stringify(props.initialData))

    // 处理嵌套的商品数据
    if (initialData.pzDealerGoodsVo) {
      selectedGoods.value = initialData.pzDealerGoodsVo

      formData.value = {
        dealerGoodsStoreId: initialData.dealerGoodsStoreId || '',
        dealerGoodsId: initialData.dealerGoodsId || '',
        dealerGoodsName: initialData.pzDealerGoodsVo.goodsName || '',
        periodStartingDate: initialData.periodStartingDate || '',
        periodEndDate: initialData.periodEndDate || '',
        points: initialData.points || 0,
        quantity: initialData.quantity || 1,
        isSale: initialData.isSale !== undefined ? initialData.isSale : true,
      }
    } else {
      formData.value = {
        ...initialData,
      }
    }
  } else {
    // 新增模式，重置表单
    resetForm()
  }
}

// 重置表单
const resetForm = () => {
  formData.value = {
    dealerGoodsStoreId: '',
    dealerGoodsId: '',
    dealerGoodsName: '',
    periodStartingDate: '',
    periodEndDate: '',
    points: 0,
    quantity: 1,
    isSale: true,
  }
}

// 获取商品列表，用于选择商品
const fetchGoods = async () => {
  try {
    goodsLoading.value = true
    const params = {
      currentPage: 1,
      pageSize: 1000, // 获取足够多的商品以供选择
    }
    const res = await fetchGoodsList(params)
    if (res.success && res.data) {
      goodsList.value = res.data.list || []
    } else {
      goodsList.value = []
      ElMessage.error(res.msg || '获取商品列表失败')
    }
  } catch (error) {
    logger.error('获取商品列表失败', error)
    ElMessage.error('获取商品列表失败')
  } finally {
    goodsLoading.value = false
  }
}

// 监听商品选择变化，自动填充商品名称
watch(
  () => formData.value.dealerGoodsId,
  (newVal) => {
    if (newVal) {
      const selected = goodsList.value.find((item) => item.dealerGoodsId === newVal)
      if (selected) {
        selectedGoods.value = selected
        formData.value.dealerGoodsName = selected.goodsName
      }
    } else {
      selectedGoods.value = null
      formData.value.dealerGoodsName = ''
    }
  },
)

// 提交表单
const submitForm = async () => {
  if (formRef.value) {
    await formRef.value.validate(async (valid) => {
      if (valid) {
        try {
          // 验证有效期
          if (
            new Date(formData.value.periodEndDate) < new Date(formData.value.periodStartingDate)
          ) {
            ElMessage.warning('结束有效期不能早于起始有效期')
            return
          }

          // 调用保存接口
          const res = await saveDealerGoodsStore(formData.value)
          if (res.success) {
            ElMessage.success('保存成功')
            emit('success')
          } else {
            ElMessage.error(res.msg || '保存失败')
          }
        } catch (error) {
          logger.error('保存商品库存失败', error)
          ElMessage.error('保存商品库存失败')
        }
      } else {
        return false
      }
    })
  }
}

// 取消提交
const cancelSubmit = () => {
  emit('close')
}

// 初始化
initFormData()
// 获取商品列表
fetchGoods()
</script>

<template>
  <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" class="store-form">
    <!-- 商品选择 -->
    <el-form-item label="选择商品" prop="dealerGoodsId">
      <div v-if="selectedGoods && props.initialData" class="selected-goods-info">
        <div class="goods-image" v-if="selectedGoods.goodsPicture">
          <el-image
            :src="selectedGoods.goodsPicture"
            fit="cover"
            style="width: 60px; height: 60px; border-radius: 4px"
            :preview-src-list="[selectedGoods.goodsPicture]"
          />
        </div>
        <div class="goods-details">
          <div class="goods-name">{{ selectedGoods.goodsName }}</div>
          <div class="goods-meta">
            <el-tag size="small">{{ selectedGoods.dealerGoodsTypeName }}</el-tag>
            <el-tag size="small" type="success">{{ selectedGoods.specifications }}</el-tag>
          </div>
        </div>
      </div>
      <el-select
        v-else
        v-model="formData.dealerGoodsId"
        placeholder="请选择商品"
        filterable
        :loading="goodsLoading"
        style="width: 100%"
      >
        <el-option
          v-for="item in goodsList"
          :key="item.dealerGoodsId"
          :label="item.goodsName"
          :value="item.dealerGoodsId"
        >
          <div class="goods-option">
            <div class="option-content">
              <el-image
                v-if="item.goodsPicture"
                :src="item.goodsPicture"
                fit="cover"
                style="width: 30px; height: 30px; border-radius: 4px; margin-right: 10px"
              />
              <span>{{ item.goodsName }}</span>
            </div>
            <div class="option-tags">
              <el-tag size="small">{{ item.dealerGoodsTypeName }}</el-tag>
            </div>
          </div>
        </el-option>
      </el-select>
    </el-form-item>

    <!-- 有效期 -->
    <el-form-item label="起始有效期" prop="periodStartingDate">
      <el-date-picker
        v-model="formData.periodStartingDate"
        type="date"
        placeholder="选择起始有效期"
        style="width: 100%"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>

    <el-form-item label="结束有效期" prop="periodEndDate">
      <el-date-picker
        v-model="formData.periodEndDate"
        type="date"
        placeholder="选择结束有效期"
        style="width: 100%"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>

    <!-- 数量和积分 -->
    <el-form-item label="数量" prop="quantity">
      <el-input-number v-model="formData.quantity" :min="1" :precision="0" style="width: 100%" />
    </el-form-item>

    <el-form-item label="积分" prop="points">
      <el-input-number v-model="formData.points" :min="0" :precision="0" style="width: 100%" />
    </el-form-item>

    <!-- 是否可售 -->
    <el-form-item label="是否可售" prop="isSale">
      <el-switch v-model="formData.isSale" active-text="可售" inactive-text="不可售" />
    </el-form-item>

    <!-- 按钮区域 -->
    <el-form-item>
      <el-button @click="cancelSubmit">取消</el-button>
      <el-button type="primary" @click="submitForm">保存</el-button>
    </el-form-item>
  </el-form>
</template>

<style lang="scss" scoped>
.store-form {
  .goods-option {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;

    .option-content {
      display: flex;
      align-items: center;
    }

    .option-tags {
      display: flex;
      gap: 4px;
    }
  }

  .selected-goods-info {
    display: flex;
    align-items: center;
    padding: 10px;
    border-radius: 4px;
    border: 1px solid #dcdfe6;

    .goods-image {
      margin-right: 15px;
    }

    .goods-details {
      flex: 1;

      .goods-name {
        font-weight: 500;
        margin-bottom: 8px;
      }

      .goods-meta {
        display: flex;
        gap: 8px;
      }
    }
  }
}
</style>
